package com.tian.arch.function.permission

import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
import java.security.Permissions

/**
 * 权限请求对象
 */
abstract class PermissionRequest {
    // 需要申请的权限
    protected var permissions: Array<out String>? = null

    // 用户同意所有的权限后的回调动作
    private var grantedAction: (() -> Unit)? = null

    fun permissions(vararg permission: String): PermissionRequest {
        this.permissions = permission
        return this
    }

    fun onGranted(block: () -> Unit): PermissionRequest {
        this.grantedAction = block
        return this
    }

    fun start() {
        if (permissions.isNullOrEmpty()) {
            throw RuntimeException("request permissions is can't be null or emptry")
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 用户同意了所有的权限
            if (agreeAllPermissions()) {
                invokeGranted()
            } else {
                requestPermissions()
            }
        } else {
            invokeGranted()
        }
    }

    /**
     * 用户同意权限
     */
    private fun invokeGranted() {
        grantedAction?.invoke()
    }

    /**
     * 用户是否同意所有的权限
     */
    private fun agreeAllPermissions(): Boolean {
        permissions?.forEach {
            val agreed = ActivityCompat.checkSelfPermission(provideContext(), it) == PackageManager.PERMISSION_GRANTED
            if (!agreed) return false
        }
        return true
    }

    /**
     * 处理权限请求的结果
     */
    fun handleReqPermissionResult(result: Map<String, Boolean>): Boolean {
        var allGranted = true
        val deniedPermission = mutableListOf<String>()
        val deniedAndNeverAskAgainPermission = mutableListOf<String>()

        result.forEach {
            if (!it.value) {
                if (shouldShowRequestPermissionRationale(it.key)) {
                    deniedPermission.add(it.key)
                } else {
                    deniedAndNeverAskAgainPermission.add(it.key)
                }
                allGranted = false
            }
        }

        if (allGranted) {
            invokeGranted()
            return true
        } else {
            if (deniedPermission.isNotEmpty()) {
                AlertDialog.Builder(provideContext()).apply {
                    setMessage("app需要如下权限才能继续正常运行 $deniedPermission")
                    setCancelable(false)
                    setPositiveButton("确定") { _, _ ->
                        permissions(*deniedPermission.toTypedArray())
                        requestPermissions()
                    }
                }.show()
            } else if (deniedAndNeverAskAgainPermission.isNotEmpty()) {
                AlertDialog.Builder(provideContext()).apply {
                    setMessage("你需要去设置当中同意如下权限 $deniedAndNeverAskAgainPermission")
                    setCancelable(false)
                    setPositiveButton("确定") { _, _ ->
                        openAppSetting()
                    }
                }.show()
            }
        }

        return false
    }


    /**
     * 是否应该显示请求权限的原因，有些手机厂商修改了这个方法，造成它不会符合预期
     */
    abstract fun shouldShowRequestPermissionRationale(vararg permission: String): Boolean
    protected abstract fun provideContext(): Context
    protected abstract fun requestPermissions()
    protected abstract fun openAppSetting()

}